package cn.xm.lingshi.controller;

import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import cn.xm.lingshi.dao.ShopDao;
import cn.xm.lingshi.dao.impl.ShopDaoImpl;
import cn.xm.lingshi.pojo.Shop;
import cn.xm.lingshi.service.ShopService;
import cn.xm.lingshi.service.impl.ShopServiceImpl;
import cn.xm.lingshi.utlis.StringUtils;

import com.alibaba.fastjson.JSON;

public class ShopServlet extends HttpServlet {

	private static final long serialVersionUID = 1L;

	public void destroy() {
		super.destroy();

	}

	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		this.doPost(request, response);
	}

	@SuppressWarnings("unchecked")
	private void doPublisShops(HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		PrintWriter out = response.getWriter();
		boolean isOK = false; // 图片上传是否成功
		boolean isOnlyText = false; // 是否为文字新闻

		String uploadPath = request.getServletContext().getRealPath("/")
				+ File.separator + "upload";
		// 如果目录不存在则创建
		File uploadDir = new File(uploadPath);
		if (!uploadDir.exists()) {
			uploadDir.mkdir();
		}
		Shop shop = new Shop();
		List<Integer> listf = new ArrayList<Integer>();
		// 1:判断表单提交的内容形式
		boolean isMultipart = ServletFileUpload.isMultipartContent(request);
		if (isMultipart) {
			// 2:创建文件上传所需的API实例
			FileItemFactory factory = new DiskFileItemFactory();
			ServletFileUpload upload = new ServletFileUpload(factory);
			// 3:解析request请求，获取FileItem对象集合
			List<FileItem> list = upload.parseRequest(request);
			// 4:循环遍历集合中的数据
			for (FileItem item : list) {
				if (item.isFormField()) {
					// 对象为普通表单
					String fieldName = item.getFieldName();
					if ("shopname".equals(fieldName)) {
						shop.setShopname(item.getString("UTF-8"));
					} else if ("brand".equals(fieldName)) {
						shop.setBrandid(Integer.valueOf(item.getString("UTF-8")));
						// news.setSummary(item.getString("UTF-8"));
					} else if ("kind".equals(fieldName)) {
						shop.setKindid(Integer.valueOf(item.getString("UTF-8")));
						// news.settId(Integer.valueOf(item.getString("UTF-8")));
					} else if ("describe".equals(fieldName)) {
						shop.setDescribe(item.getString("UTF-8"));
						// news.setAuthor(item.getString("UTF-8"));
					} else if ("kucun".equals(fieldName)) {
						shop.setKucun(Integer.valueOf(item.getString("UTF-8")));
						// news.setContent(item.getString("UTF-8"));
					} else if ("shoporice".equals(fieldName)) {
						shop.setShoporice(Integer.valueOf(item
								.getString("UTF-8")));
						// news.setContent(item.getString("UTF-8"));
					} else if ("flav".equals(fieldName)) {
						String values = item.getString("UTF-8");
						
						if (values != null && values.length() > 0) {
							for (int i = 0; i < values.length(); i++)
								listf.add(Integer.valueOf(values.substring(i,i+1)));
						}

					}
				} else {
					// 对象为文件表单
					String name = item.getName();
					if (name != null && !"".equals(name)) {
						// 控制文件的上传的类型
						if (!StringUtils.checkImg(name)) {
							out.println("<script>alert('新闻图片的格式不正确，请重新选择');history.back();</script>");
						} else {
							String fileName = StringUtils.getNewName(name);
							shop.setShopimg(fileName);
							// 远程服务器的文件地址
							File file = new File(uploadPath, fileName);
							item.write(file);
							isOK = true;
						}
					} else {
						isOnlyText = true;
					}

				}

			}
		}
		if (isOnlyText || isOK)

		{
			// 调用业务逻辑层
			ShopService shopService = new ShopServiceImpl();
			ShopDao shopdao = new ShopDaoImpl();
			int result1 = shopService.addShop(shop);
			int shopid = shopdao.getShop(shop.getShopname());
			int result2 = shopService.addShopFlavour(listf, shopid);
			if (result1 == 1) {
				// 发布成功
				out.println("<script>alert('恭喜您，商品添加成功');location.href='newslist.jsp';</script>");
				// 发布失败
			} else {
				out.println("<script>alert('商品添加失败');history.back();</script>");
			}

		}
	}

	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		response.setContentType("text/html;charset=UTF-8");
		PrintWriter out = response.getWriter();
		// 接收请求数据
		request.setCharacterEncoding("UTF-8");
		// 接收处理的参数
		String action = request.getParameter("action");
		if (action != null && !"".equals(action)) {
			if ("shopadd".equals(action)) {
				try {
					this.doPublisShops(request, response);
				} catch (Exception e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			} 
		} else {
			response.sendRedirect("index.jsp");
		}
	}

	public void init() throws ServletException {
		// Put your code here
	}

}
